<?php

namespace App\Console\Commands;

use App\Library\Logic\ShopImageLogic;
use App\Library\Logic\ShopProductLogic;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;

class ShopProductImageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:shopProductImage {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $shopProduct = ShopProductLogic::findBySerialNumber($serialNumber);
        if (is_null($shopProduct)) return;
        $this->handleVideo($shopProduct);
        $this->handleMain($shopProduct);
        $this->handleDesc($shopProduct);
        $shopProduct->save();
    }

    /**
     * handleMain
     * @param Model $shopProduct
     * @return void
     */
    private function handleMain(Model $shopProduct): void
    {
        $where = ['imgType' => 1, 'imgSourceType' => 4, 'imgSourceId' => $shopProduct->product_id];
        $pluck = ShopImageLogic::query()->where(humpToLine($where))->orderBy('img_is_cover')->orderBy('img_sort')
            ->pluck('img_url');
        $shopProduct->main_img_ids = $pluck->count() > 0 ? $pluck->toArray() : null;
        $shopProduct->save();
    }

    /**
     * handleDesc
     * @param Model $shopProduct
     * @return void
     */
    private function handleDesc(Model $shopProduct): void
    {
        $where = ['imgType' => 1, 'imgSourceType' => 5, 'imgSourceId' => $shopProduct->product_id];
        $pluck = ShopImageLogic::query()->where(humpToLine($where))->orderBy('img_sort')
            ->pluck('img_url');
        $shopProduct->desc_img_ids = $pluck->count() > 0 ? $pluck->toArray() : null;
        $shopProduct->save();
    }

    /**
     * handleVideo
     * @param Model $shopProduct
     * @return void
     */
    private static function handleVideo(Model $shopProduct): void
    {
        $where = ['imgType' => 2, 'imgSourceType' => 4, 'imgSourceId' => $shopProduct->product_id];
        $shopProduct->video_id = ShopImageLogic::valueByWhere($where, null, 'imgUrl');
        $shopProduct->save();
    }
}
